package com.example.springboot_sdse_air.service;

import java.io.*;
import java.net.URL;
import java.nio.file.*;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot_sdse_air.entity.Pdf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 功能：
 * 作者：王彬 202200111149
 * 日期：2025-04-28 8:14
 */
@Service
public class ZipService {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @Resource
    PdfService pdfService;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
    private String PARENT_FOLDER_NAME;
    private String ZIP_NAME;


    // 下载zip文件到本地
    public File downloadZip(String fileUrl, Integer pdf_id) throws IOException {
        URL url = new URL(fileUrl);
        Pdf pdf = pdfService.getById(pdf_id);
        PARENT_FOLDER_NAME = pdf.getParentFolderName();
        ZIP_NAME = FileUtil.mainName(pdf.getName());
        String zipFileName = ZIP_NAME + ".zip";
        String targetDir = ROOT_PATH + File.separator + "UserPdf" + File.separator + PARENT_FOLDER_NAME;

        Path targetPath = Paths.get(targetDir, zipFileName);

        try (InputStream in = url.openStream()) {
            Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
        }

        return targetPath.toFile();
    }

    // 解压zip文件到指定文件夹
    public File unzip(File zipFile) throws IOException {
        String destDir = ROOT_PATH + File.separator + "UserPdf" + File.separator + PARENT_FOLDER_NAME;
        File originFolder = new File(destDir);
        File destFolder = new File(destDir, ZIP_NAME);
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile.toPath()))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File newFile = new File(destFolder, entry.getName());
                if (entry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    // 确保父文件夹存在
                    String new_file_parent = newFile.getParent();
                    File parentDir = new File(newFile.getParent());
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }

        // 递归删除解压缩文件夹中不需要的文件
        deleteUnwantedFiles(originFolder);

        return destFolder;
    }

    public void deleteUnwantedFiles(File folder) {
        // 遍历文件夹，删除不需要的文件
        if (folder.isDirectory()) {
            for (File file : Objects.requireNonNull(folder.listFiles())) {
                if (file.isDirectory()) {
                    deleteUnwantedFiles(file);  // 递归删除子文件夹
                } else {
                    String mainName = FileUtil.mainName(file);  // 文件名
                    String extName = FileUtil.extName(file);  // 文件拓展名
                    if (("pdf".equals(extName) && !ZIP_NAME.equals(mainName)) || "json".equals(extName) || "zip".equals(extName)) {
                        FileUtil.del(file);
                    } else if ("md".equals(extName)) {
                        String newName = ZIP_NAME + ".md";
                        FileUtil.rename(file, newName, true);
                    }
                }
            }
        }
    }
}
